package com.feasy.generator.generatorcode.service;

import com.feasy.generator.generatorcode.utils.GeneratorUtils;
import com.feasy.generator.managedb.utils.DataBaseUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.sql.Connection;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;

@Service
public class GeneratorCodeServiceImpl implements GeneratorCodeService {
    @Override
    public byte[] generatorCode(String dbtype, String ip, String port, String dbName, String username, String password, String tableName, String packagePath, String author, String email) {

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);

        String jdbcUrl = DataBaseUtils.getJdbcUrl(dbtype, ip, port, dbName);
        Connection connection = DataBaseUtils.getConnection(dbtype, jdbcUrl, username, password);

        String tableComment = DataBaseUtils.getTableComment(connection, tableName, dbtype);

        Connection connection1 = DataBaseUtils.getConnection(dbtype, jdbcUrl, username, password);
        //查询列信息
        String sql =DataBaseUtils.getTableColumnSql(dbtype, tableName);
        List<Map<String, Object>> columns = DataBaseUtils.queryMapList(connection1, sql);

        //生成代码
        // 是否生成APP接口 1是0否
        String intercode = "0";
        try {
            GeneratorUtils.generatorCode(tableName, tableComment, columns, intercode, zip, packagePath, author, email);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();

    }
}
